﻿using AutoMapper;
using BBICMS.Application.ViewModels;
using BBICMS.Application.ViewModels.Front;
using BBICMS.Model;
using BBICMS.Repository;

using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BBICMS.WebUI.Controllers
{

    public class ProductsController : BaseController
    {

  

        //public ActionResult Serie(int id, int? page = 1)
        //{

        //    var defaultLang = LanguageHelper.GetCurrentCulture();
        //    var psl = _unit.SerieLangs.GetFilteredElements(c => c.CultureName == defaultLang && c.SerieId == id, c => c.Serie).FirstOrDefault();
        //    if (psl == null)
        //        return HttpNotFound();

        //    ProductListBySerieVM vm = new ProductListBySerieVM();
        //    vm.Serie = Mapper.Map<SerieLang, SerieVM>(psl);
        //    vm.SerieId = id;
        //    vm.PageIndex = (page ?? 1) - 1;
        //    vm.PageSize = 15;         

        //    var query = _unit.Products.GetAll().Where(p => p.SerieId == id && p.Active);
        //    var orgProducts = query.OrderByDescending(p => p.Id).Skip(vm.PageIndex * vm.PageSize).Take(vm.PageSize).ToList();

        //    vm.TotalCount = query.Count();

        //    var products = Mapper.Map<List<Product>, List<ProductVM>>(orgProducts);

        //    vm.ProductList = new StaticPagedList<ProductVM>(products, vm.PageIndex + 1, vm.PageSize, vm.TotalCount);

        //    return View(vm);
        //}

        //public PartialViewResult LasterSeries()
        //{
        //    var series = GetSeries().Where(s => s.Active).OrderByDescending(s => s.Id).Take(8);
        //    return PartialView("_LasterSeries",series);
        //}

        //public PartialViewResult RecommendSeries()
        //{
        //    var series = GetSeries().Where(s=>s.Active && s.Recommend).OrderByDescending(s => s.Id).Take(12);
        //    return PartialView("_RecommendSeries", series);
        //}


        //public PartialViewResult SameSerieProducts(int id, int serieId)
        //{
        //    var products = _unit.Products.FindBy(p => p.SerieId == serieId && p.Id!=id).OrderByDescending(p=>p.Id);
        //    return PartialView("_SameSerieProducts", products);
        //}
        //private List<SerieVM> GetSeries()
        //{
        //    var cu = LanguageHelper.GetCurrentCulture();
        //    var pcls = _unit.SerieLangs.GetFilteredElements(l => l.CultureName.Equals(cu, StringComparison.InvariantCultureIgnoreCase), l => l.Serie).ToList();
        //    var series = Mapper.Map<List<SerieLang>, List<SerieVM>>(pcls);
        //    return series;
        //}

        public ActionResult Index(string Keyword, int? CategoryId, int? page = 1)
        {
            ProductsListVM vm = new ProductsListVM
            {
                PageIndex = (page ?? 1) - 1,
                PageSize = 12,

                ProductSearchVM = new ProductSearchVM
                {
                    Keyword = Keyword,
                    CategoryId = CategoryId

                }
            };

            var defaultLang = LanguageHelper.GetCurrentCulture();

            var query = _unit.Products.GetAll().Where(p=>p.Active && p.Lang == defaultLang);
            if (CategoryId > 0)
            {
                query = query.Where(p => p.CategoryId == CategoryId);
            }       


            if (!string.IsNullOrEmpty(Keyword))
            {
                query = query.Where(p => p.ProductNo.Contains(Keyword));
            }

            var orgProducts  = query.OrderByDescending(p=>p.Id).Skip(vm.PageIndex * vm.PageSize).Take(vm.PageSize).ToList();

            vm.TotalCount = query.Count();

            var products = Mapper.Map<List<Product>,List<ProductVM>>(orgProducts);

            vm.ProductList = new StaticPagedList<ProductVM>(products, vm.PageIndex + 1, vm.PageSize, vm.TotalCount);
     
         
            var pcls = _unit.ProductCategoryLangs.GetFilteredElements(c => c.CultureName == defaultLang, c => c.Category).ToList();
            var categories = Mapper.Map<List<ProductCategoryLang>, List<ProductCategoryVM>>(pcls);
            var selectCategories = new SelectList(categories.OrderByDescending(c => c.Importance).ToList(), "Id", "Title");
            ViewBag.Categories = selectCategories;
        

            return View(vm);
        }
        public PartialViewResult LasterProducts()
        {
            var orgProducts = _unit.Products.GetAll().Where(p => p.Active).OrderByDescending(p => p.AddedDate).Take(6).ToList();
            var products = Mapper.Map<List<Product>, List<ProductVM>>(orgProducts);
            return PartialView("_LasterProducts", products);
        }
        

          public PartialViewResult RecommendProducts()
        {
            var orgProducts = _unit.Products.GetAll().Where(p => p.Active && p.Recommend).OrderByDescending(p => p.AddedDate).Take(12).ToList();
            var products = Mapper.Map<List<Product>, List<ProductVM>>(orgProducts);
            return PartialView("_RecommendProducts", products);
        }



        //[HttpPost()]
        //public ActionResult UploadImage(HttpPostedFileBase image, int id)
        //{
        //    JsonResult result;
        //    Product product;
        //    Random rand = new Random();
        //    string unique;
        //    string ext;
        //    string fileName;
        //    string path;

        //    unique = rand.Next(1000000).ToString();

        //    ext = Path.GetExtension(image.FileName).ToLower();

        //    fileName = string.Format("{0}-{1}{2}", id, unique, ext);

        //    path = Path.Combine(
        //        HttpContext.Server.MapPath(Config.ImagesFolderPath), fileName);

        //    if (ext == ".png" || ext == ".jpg")
        //    {
        //        product = _unit.Products.GetById(id);

        //        if (product != null)
        //        {
        //            product.Thumbnail = fileName;
        //            _unit.Products.Update(product);
        //            _unit.SaveChanges();

        //            image.SaveAs(path);
        //            result = this.Json(new
        //            {
        //                thumbnailUrl = string.Format("{0}{1}",
        //                Config.ImagesUrlPrefix, fileName)
        //            });
        //        }
        //        else
        //        {
        //            result = this.Json(new
        //            {
        //                status = "error",
        //                statusText = 
        //                    string.Format("There is no product with the Id of " + 
        //                        "'{0}' in the system.", id)
        //            });
        //        }
        //    }
        //    else
        //    {
        //        result = this.Json(new
        //        {
        //            status = "error",
        //            statusText = "Unsupported image type. Only .png or " + 
        //                ".jpg files are acceptable."
        //        });
        //    }

        //    return result;
        //}




        [AllowAnonymous]
        public ActionResult Detail(int id)
        {
          
            var product = _unit.Products.GetById(id);
            product.ViewCount++;
            _unit.Products.Update(product);
            _unit.SaveChanges();

            ProductDetailVM vm = Mapper.Map<Product, ProductDetailVM>(product);

            var defaultLang = LanguageHelper.GetCurrentCulture();
            var pcl = _unit.ProductCategoryLangs.GetFirstOrDefault(c => c.CultureName == defaultLang && c.CategoryId == product.CategoryId, c => c.Category);
            if(pcl!=null)
                vm.CategoryTitle = pcl.Title;
         

            //var pcolorls = _unit.ColorLangs.FindBy(c => c.CultureName == defaultLang).ToList();

      


            if (vm != null)
            {
                return View(vm);
            }            
            return View("NotFound");

        }


        protected override void Dispose(bool disposing)
        {
            this._unit.Dispose();
            base.Dispose(disposing);
        }


        // *********************************** // 
        // ********* Offline Support ********* //
        // *********************************** // 
        [AllowAnonymous]
        public ActionResult Offline()
        {
            return View();
        }

        public ActionResult ReviewOffline()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult Manifest()
        {
            this.Response.ContentType = "text/cache-manifest";
            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            string viewName = "Manifest";

#if DEBUG
            viewName = "Manifest-Debug";
#endif

            return View(viewName);
        }
    }
}
